#!/bin/sh
#
# Script to update PowerDNS recursor configuration fragment
#
# N.B. Resolvconf may run us even if pdns not running.
# If pdns is installed then we go ahead and update
# the pdns configuration file in case pdns is started later.
#
# Assumption: On entry, PWD contains the resolv.conf-type files
#
# Licensed under the GNU GPL. See /usr/share/common-licenses/GPL
#
# History:
# April 2005: Written by Jack Bates <ms419@freezone.co.uk> and
#             Thomas Hood <jdthood@yahoo.co.uk>

set -e
PATH=/bin:/sbin

DEFAULT=/etc/default/pdns
[ -f $DEFAULT ] && . $DEFAULT

if [ -z "${RESOLVCONF_UPDATE_FORWARDERS:-}" ]; then
    echo "Warning: \$RESOLVCONF_UPDATE_FORWARDERS not defined in $DEFAULT." >&2
    echo "         Pulling the emergency brake..." >&2
    exit 0
fi

case $RESOLVCONF_UPDATE_FORWARDERS in
    y*|Y*|1|on|On|true|True|TRUE) :;;
    *)
        echo "Not updating PowerDNS, disabled in $DEFAULT." >&2
        exit 0
    ;;
esac

[ -x /usr/sbin/pdns_server ] || exit 0
[ -x /lib/resolvconf/list-records ] || exit 1

RUN_DIR=/var/run
CONF_FILE="$RUN_DIR/pdns.recursors"
TMP_FILE="${CONF_FILE}_new.$$"

# Get list of records, excluding our own
RSLVCNFFILES="$(/lib/resolvconf/list-records | sed -e '/^lo.pdns$/d')"

clean_up() { rm -f "$TMP_FILE" ; }
trap clean_up EXIT
clean_up

# Convert nameserver lines to recursor statements, without duplicates
if [ "$RSLVCNFFILES" ]; then
  sed -n "
    s/^nameserver[[:space:]]\+/recursor=/
    # If no substitution (not a nameserver line) then skip line
    T
    # Append hold space (i.e., previous recursor statements) to pattern space
    G
    # If this line is a duplicate then skip line
    /\(^.*\n\).*\1/d
    # Disable 127.0.0.1 lines, can cause a dns loop.
    /=127\./d
    # Copy pattern space, including current line, to hold space
    h
    # Print current line
    P
  " $RSLVCNFFILES > "$TMP_FILE"
else
  :> "$TMP_FILE"
fi

if [ "$1" = "-i" ]; then
  mv -f "$TMP_FILE" "$CONF_FILE"
  exit 0
fi

# Reload pdns unless we know its configuration file hasn't changed
if [ -x /usr/bin/diff ] && [ -f "$CONF_FILE" ] && /usr/bin/diff -q "$CONF_FILE" "$TMP_FILE" > /dev/null ; then
  # No change
  rm -f "$TMP_FILE"
else
  mv -f "$TMP_FILE" "$CONF_FILE"
  [ -x /etc/init.d/pdns ] && ps -C pdns_server > /dev/null && invoke-rc.d pdns reload || :
fi

